<?php
namespace app\service;

use GuzzleHttp\Client;
use think\facade\Log;
use Exception;

class AiStreamHandler
{
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function handle(string $url, array $headers, array $data, callable $callback)
    {
        try {
            Log::info('AI请求参数：' . json_encode([
                'url' => $url,
                'model' => $data['model'],
                'message_count' => count($data['messages'])
            ]));
            
            $response = $this->client->post($url, [
                'headers' => $headers,
                'json' => $data,
                'stream' => true,
                'timeout' => 30,
                'verify' => false
            ]);
            
            $buffer = '';
            $body = $response->getBody();
            
            while (!$body->eof()) {
                $chunk = $body->read(1024);
                $buffer .= $chunk;
                
                while (($pos = strpos($buffer, "\n")) !== false) {
                    $line = substr($buffer, 0, $pos);
                    $buffer = substr($buffer, $pos + 1);
                    
                    if (strpos($line, 'data: ') === 0) {
                        $json = substr($line, 6);
                        if ($json === '[DONE]') {
                            break;
                        }
                        
                        $data = json_decode($json, true);
                        if (isset($data['choices'][0]['delta']['content'])) {
                            $callback($data['choices'][0]['delta']['content']);
                        }
                    }
                }
            }
        } catch (Exception $e) {
            Log::error('AI服务请求失败：' . $e->getMessage());
            throw new Exception('AI服务请求失败: ' . $e->getMessage());
        }
    }
} 